package com.mj.mafeed.service;

import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import android.content.Context;
import android.net.Uri;

import com.mj.mafeed.bean.CartItemJSON;
import com.mj.mafeed.bean.OrderJSON;
import com.mj.mafeed.bean.OrderListJSON;
import com.mj.mafeed.config.Constants;
import com.mj.mafeed.dao.CartItemDao;
import com.mj.mafeed.util.HttpUtils;

/**
 * 我的订单
 * @author zhaominglei
 * @date 2014-12-16
 * 
 */
public class OrderService extends BaseService {
	private CartItemDao cartItemDao = new CartItemDao();
	
	/**
	 * 订单列表
	 */
	public OrderListJSON getOrder(String referer, String keyword, int page, String username, String sign) {
		StringBuilder url = new StringBuilder(Constants.MEMBER_ORDER_URL);
		url.append("?p=").append(page).append("&keyword=").append(Uri.encode((keyword == null)?"":keyword));
		url.append("&username=").append(username).append("&sign=").append(sign);
		String result = HttpUtils.doGet(url.toString());
		if (result != null && !result.equals("")) {
			try {
				OrderListJSON orderList = new ObjectMapper().readValue(result, OrderListJSON.class);
				return (orderList != null) ? orderList : null; 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 提交订单
	 */
	public OrderJSON submitOrder(Context context, Long receiverId, Long paymentMethodId, Long shippingMethodId, Boolean isInvoice, 
			String invoiceinfo,	String referer, String username, String sign) {
		List<CartItemJSON> cartItemJSONs = cartItemDao.getAll(context);
		if (cartItemJSONs != null && cartItemJSONs.size() > 0) {
			Long cartId = cartItemJSONs.get(0).getCartId();
			if (cartId != null && cartId.intValue() > 0) {
				StringBuilder param = new StringBuilder();
				param.append("username=").append(username).append("&sign=").append(sign);
				param.append("&cartId=").append(cartId).append("&receiverId=").append(receiverId);
				param.append("&paymentMethodId=").append(paymentMethodId).append("&shippingMethodId=").append(shippingMethodId);
				param.append("&isInvoice=").append(isInvoice).append("&invoiceinfo=").append(invoiceinfo);
				String result = HttpUtils.doPost(Constants.MEMBER_ORDER_SUBMIT_URL, param.toString());
				if (result != null && !result.equals("")) {
					try {
						OrderJSON orderJSON = new ObjectMapper().readValue(result, OrderJSON.class);
						if (orderJSON != null) { 
							cartItemDao.deleteAll(context);
							return orderJSON;
						} 
					}  catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return null;
	}
}
